#include "stdafx.h"
#ifdef _DEBUG
	#undef THIS_FILE
	static char THIS_FILE[] = __FILE__;
	#define new DEBUG_NEW
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
const char __DeBase64Tab__[] =
{
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	62,        // '+'
	0, 0, 0,
	63,        // '/'
	52, 53, 54, 55, 56, 57, 58, 59, 60, 61,        // '0'-'9'
	0, 0, 0, 0, 0, 0, 0,
	0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
	13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,        // 'A'-'Z'
	0, 0, 0, 0, 0, 0,
	26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
	39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,        // 'a'-'z'
};
const char __EnBase64Tab__[]={"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"};
///////////////////////////////////////////////////////////////////////////////////////////////////
UMYWINDOW9_API long base64_Encode(LPSTR pDest,LPCSTR pSrc,long lSrcLen)
{
	BYTE c1,c2,c3;
	long i=0,lDestLen(0),lDiv(lSrcLen/3),lMod(lSrcLen%3);
	for(;i<lDiv;++i,lDestLen+=4)
	{
		c1 = *pSrc++;
		c2 = *pSrc++;
		c3 = *pSrc++;
		*pDest++ = __EnBase64Tab__[c1>>2];
		*pDest++ = __EnBase64Tab__[((c1<<4)|(c2>>4))&0X3F];
		*pDest++ = __EnBase64Tab__[((c2<<2)|(c3>>6))&0X3F];
		*pDest++ = __EnBase64Tab__[c3&0X3F];
	}
	if(lMod==1)
	{
		c1 = *pSrc++;
		*pDest++ = __EnBase64Tab__[(c1&0XFC)>>2];
		*pDest++ = __EnBase64Tab__[((c1&0X03)<<4)];
		*pDest++ = '=';
		*pDest++ = '=';
		lDestLen += 4;
	}
	else if(lMod==2)
	{
		c1 = *pSrc++;
		c2 = *pSrc++;
		*pDest++ = __EnBase64Tab__[(c1&0XFC)>>2];
		*pDest++ = __EnBase64Tab__[((c1&0X03)<<4)|((c2&0XF0)>>4)];
		*pDest++ = __EnBase64Tab__[((c2&0X0F)<<2)];
		*pDest++ = '=';
		lDestLen += 4;
	}
	*pDest = 0;
	return(lDestLen);
}

UMYWINDOW9_API long base64_Decode(LPSTR pDest,LPCSTR pSrc,long lSrcLen,long maxDest)
{
	long lDestLen=0,nValue=0,i=0;
	for(;i<lSrcLen;i+=4)
	{
		nValue = __DeBase64Tab__[*pSrc++]<<18;
		nValue += __DeBase64Tab__[*pSrc++]<<12;
		*pDest++ = BYTE((nValue&0X00FF0000)>>16);
		if(++lDestLen>=maxDest) break;
		if(*pSrc!='=')
		{
			nValue += __DeBase64Tab__[*pSrc++]<<6;
			*pDest++ = (nValue&0X0000FF00)>>8;
			if(++lDestLen>=maxDest) break;

			if(*pSrc!='=')
			{
				nValue += __DeBase64Tab__[*pSrc++];
				*pDest++ = nValue&0X000000FF;
				if(++lDestLen>=maxDest) break;
			}
		}
	}
    *pDest = 0;
    return(lDestLen);
}
